package org.lanyu.springainovel.chat.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.lanyu.springainovel.common.entity.AiModel;
import org.lanyu.springainovel.common.service.AiModelService;
import org.lanyu.springainovel.common.vo.RestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import java.util.List;

@Tag(name = "模型管理", description = "AI模型管理相关接口")
@RestController
@RequestMapping("/aiModel")
public class AiModelController {
    @Autowired
    private AiModelService aiModelService;

    @Value("${ai.icon-upload-path}")
    private String iconUploadPath;

    @Operation(summary = "获取所有模型")
    @GetMapping("/list")
    public RestVO<List<AiModel>> list(
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String tags,
            @RequestParam(required = false) String vendor,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String context) {
        return RestVO.success(aiModelService.findByFilters(type, tags, vendor, status, context));
    }

    @Operation(summary = "根据ID获取模型")
    @GetMapping("/get")
    public RestVO<AiModel> get(@RequestParam Long id) {
        AiModel model = aiModelService.findById(id);
        return RestVO.success(model);
    }

    @Operation(summary = "新增或更新模型")
    @PostMapping("/save")
    public RestVO<AiModel> save(@RequestBody AiModel model) {
        return RestVO.success(aiModelService.save(model));
    }

    @Operation(summary = "删除模型")
    @PostMapping("/delete")
    public RestVO<Void> delete(@RequestParam Long id) {
        aiModelService.deleteById(id);
        return RestVO.success(null);
    }

    @Operation(summary = "上传模型图标")
    @PostMapping("/uploadIcon")
    public RestVO<String> uploadIcon(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return RestVO.fail("文件为空");
        }
        String originalFilename = file.getOriginalFilename();
        String ext = StringUtils.getFilenameExtension(originalFilename);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = uuid + (ext != null ? "." + ext : "");
        // 目标路径（从配置文件读取�?
        String staticPath = iconUploadPath;
        File dir = new File(staticPath);
        if (!dir.exists()) dir.mkdirs();
        File dest = new File(dir, fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return RestVO.fail("上传失败: " + e.getMessage());
        }
        // 返回可访问的相对路径
        String url = "/icon/" + fileName;
        return RestVO.success(url);
    }

    @Operation(summary = "获取所有模型图标")
    @GetMapping("/icons")
    public RestVO<List<String>> getAllIcons() {
        List<String> icons = new ArrayList<>();
        String staticPath = iconUploadPath;
        File iconDir = new File(staticPath);
        
        if (iconDir.exists() && iconDir.isDirectory()) {
            File[] files = iconDir.listFiles((dir, name) -> {
                String lowerName = name.toLowerCase();
                return lowerName.endsWith(".png") || lowerName.endsWith(".jpg") || 
                       lowerName.endsWith(".jpeg") || lowerName.endsWith(".gif") || 
                       lowerName.endsWith(".svg");
            });
            
            if (files != null) {
                for (File file : files) {
                    icons.add("/icon/" + file.getName());
                }
            }
        }
        
        return RestVO.success(icons);
    }
}
